import { FC, useContext, useMemo } from "react";
import ReactECharts from 'echarts-for-react';
import styles from "./index.module.less";
import { MarkerItem } from "../BGContainer";
import { TrendData } from "../BGContainer/useCharts";
import classNames from "classnames";
import dayjs from 'dayjs';
import { BigScreenContext } from "../../context/BigScreenContext";
import { sample } from "lodash";

interface MarkerInfoProps {
  selectedMarker: MarkerItem | null;
  markerPixelPosition: { x: number; y: number } | null;
  viewportSize: { width: number; height: number };
  trendData?: TrendData[]; // 趋势图数据
  isQuestionMode?: boolean; // 是否为question模式
  hideContentTitle?: boolean; // 是否隐藏内容标题
  hideCloseIcon?: boolean; // 是否隐藏关闭按钮
  predictTime?: string; // 预测时间点，格式"YYYY-MM-DD HH:mm:ss"
  upperLimit?: number; // 上限值
  lowerLimit?: number; // 下限值
  isTransparent?: boolean; // 添加透明度控制属性
  onClose: () => void;
  onSpanClick?: (currentTrendData?: any) => void; // 修改点击spanIcon的回调函数，传递当前趋势数据
  onChartPointClick?: (params: { name: string; value: any; dataIndex: number; seriesIndex: number; }) => void; // 点击图表上的点的回调函数
}

const MarkerInfo: FC<MarkerInfoProps> = ({
  selectedMarker,
  markerPixelPosition,
  viewportSize,
  hideContentTitle,
  hideCloseIcon,
  trendData = [], // 默认为空数组
  isQuestionMode = false, // 默认不是question模式
  predictTime, // 预测时间点
  upperLimit, // 上限值
  lowerLimit, // 下限值
  isTransparent = false, // 默认不透明
  onClose,
  onSpanClick,
  onChartPointClick
}) => {
  const { chatRef, currentKey } = useContext(BigScreenContext);
  // 为当前选中的标记找到对应的趋势图数据
  const currentTrendData = useMemo(() => {
    if (!selectedMarker || trendData.length === 0) return null;
    // 在question模式下，尝试根据标记的title匹配趋势数据
    if (isQuestionMode) {
      const matchedData = trendData.find(item => item.evaluationItemName === selectedMarker.title);
      return matchedData || trendData[0];
    }

    // 在param模式下，返回所有趋势数据
    if (currentKey === 'param') {
      return trendData;
    }

    // 在其他模式下，直接返回第一条数据
    return trendData[0];
  }, [selectedMarker, trendData, isQuestionMode, currentKey]);

  // 创建图表选项
  const getChartOptions = (type: string) => {
    // 基础颜色映射
    const colorMap = {
      'red': 'rgba(255, 77, 79, 1)',
      'yellow': 'rgba(250, 173, 20, 1)',
      'green': 'rgba(82, 196, 26, 1)',
      'default': 'rgba(3, 251, 255, 1)'
    };

    // 获取主要颜色
    const mainColor = colorMap[type as keyof typeof colorMap] || colorMap.default;

    // 辅助颜色数组（用于多线图）
    const colorArray = [
      mainColor,
      'rgba(255, 145, 0, 1)',
      'rgba(0, 208, 132, 1)',
      'rgba(51, 133, 255, 1)',
      'rgba(245, 34, 45, 1)'
    ];

    // 创建上下限的标记线和区域配置
    const getLimitMarkOptions = () => {
      // 检查是否同时有上限和下限
      if (upperLimit !== undefined && lowerLimit !== undefined) {
        return {
          markLine: {
            silent: true,
            symbol: 'none',
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.5)',
              type: 'dashed',
              width: 1
            },
            label: {
              show: false,
            },
            data: [
              { yAxis: upperLimit },
              { yAxis: lowerLimit }
            ]
          },
          markArea: {
            silent: true,
            itemStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            },
            data: [
              [
                { yAxis: lowerLimit },
                { yAxis: upperLimit }
              ]
            ]
          }
        };
      }

      return {};
    };
    // 判断是否有趋势图数据
    if (currentTrendData) {
      // 判断是单线图还是多线图
      const isMultiLine = Array.isArray(currentTrendData) && currentTrendData.length > 1;

      if (isMultiLine) {
        // 多线图情况 - param模式
        const allTrendData = currentTrendData as TrendData[];

        // 找出所有时间点并排序
        let allTimes: string[] = [];
        allTrendData.forEach(trend => {
          allTimes = [...allTimes, ...trend.times];
        });
        // 去重并排序
        allTimes = [...new Set(allTimes)].sort((a, b) =>
          new Date(a).getTime() - new Date(b).getTime()
        );

        // 格式化为X轴标签
        const xAxisData = allTimes.map(time => {
          try {
            return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
          } catch (err) {
            return time;
          }
        });
        // 构建多条系列数据
        const series = allTrendData.map((trend, index) => {
          const seriesItem = {
            name: trend.tagDesc || `数据${index + 1}`,
            data: trend.values,
            tagDesc: trend.tagDesc,
            type: 'line',
            smooth: true,
            showSymbol: false,
            itemStyle: {
              color: '#fff',
              borderColor: colorArray[index % colorArray.length],
              borderWidth: 1,
            },
            lineStyle: {
              color: colorArray[index % colorArray.length],
              width: 2,
            },
            ...(index === 0 ? getLimitMarkOptions() : {}) // 只在第一条线上添加限制标记
          };

          return seriesItem;
        });
        return {
          grid: {
            left: 10, // 增加左侧空间以显示y轴刻度
            right: 15,
            top: 30, // 为图例留出空间
            bottom: 10,
            containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (params: any) {
              let result = `<div style="font-weight:bold;margin-bottom:3px;">${params[0].axisValue}</div>`;
              // 添加所有系列的数据
              params.forEach((param: any) => {
                const color = colorArray[param.seriesIndex % colorArray.length]; // 修改此行以确保颜色与折线图系列颜色一致
                result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${color}"></span>
                  <span style="flex:1">${param.seriesName}:</span>
                  <span style="font-weight:bold;float:right">${param.value}</span>
                </div>`;
              });

              return result;
            },
            backgroundColor: 'rgba(50,50,50,0.9)',
            borderColor: 'rgba(255,255,255,0.3)',
            textStyle: {
              color: '#fff',
              fontSize: 12
            },
            padding: [8, 10]
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
              hideOverlap: true,
              formatter: (value: string) => {
                return dayjs(value).format('HH:mm');
              }
            },
            splitNumber: 4
          },
          yAxis: {
            type: 'value',
            show: true,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: true, lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } },
            axisLabel: {
              show: true,
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
              formatter: (value: number) => value.toFixed(2)
            },
            splitNumber: 4, // 建议4~6之间
            // 修改：考虑上下限值的y轴范围设置
            min: (value: any) => {
              const calcMin = Math.floor(value.min) * 0.9;
              return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
            },
            max: (value: any) => {
              const calcMax = Math.ceil(value.max) * 1.1;
              return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
            },
          },
          legend: {
            type: 'scroll', 
            orient: 'horizontal',
            width: '100%',
            pageIconColor: '#aaa', 
            pageIconInactiveColor: '#2f4554', 
            data: series.map(item => item.tagDesc),
            right: 0,
            top: 0,
            textStyle: {
              color: '#fff',
            },
            pageTextStyle: {
              color: '#ffffff'  // 设置为白色
            }
          },
          series: series,
        };
      } else {
        // 单线图情况 - 原有模式
        const singleTrendData = Array.isArray(currentTrendData) ? currentTrendData[0] : currentTrendData;

        // 格式化日期时间，只显示时:分
        const xAxisData = singleTrendData.times.map(time => {
          try {
            return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
          } catch (err) {
            return time;
          }
        });
        // 处理有predictTime的情况
        if (predictTime) {
          // 将时间和值数据分割为实际值和预测值
          const splitIndex = singleTrendData.times.findIndex(time =>
            dayjs(time).isAfter(dayjs(predictTime)) || dayjs(time).isSame(dayjs(predictTime))
          );

          // 如果找不到分割点或者所有数据都是实际值，则使用默认的单线图
          if (splitIndex === -1 || splitIndex >= singleTrendData.times.length) {
            return {
              grid: {
                left: 10,
                right: 15,
                top: 10, // 为图例留出空间
                bottom: 10,
                containLabel: true
              },
              tooltip: {
                trigger: 'axis',
                formatter: function (params: any) {
                  const dataIndex = params[0].dataIndex;
                  const time = singleTrendData.times[dataIndex];
                  const value = singleTrendData.values[dataIndex];

                  let result = `<div style="font-weight:bold;margin-bottom:3px;">${dayjs(time).format('YYYY-MM-DD HH:mm:ss')}</div>`;

                  // 添加实际值
                  result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                    <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${mainColor}"></span>
                    <span style="flex:1">实际值:</span>
                    <span style="font-weight:bold;float:right">${value}</span>
                  </div>`;

                  // 添加上限值和下限值（如果存在）
                  if (upperLimit !== undefined) {
                    result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                      <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
                      <span style="flex:1">上限值:</span>
                      <span style="font-weight:bold;float:right">${upperLimit}</span>
                    </div>`;
                  }

                  if (lowerLimit !== undefined) {
                    result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                      <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
                      <span style="flex:1">下限值:</span>
                      <span style="font-weight:bold;float:right">${lowerLimit}</span>
                    </div>`;
                  }

                  return result;
                },
                backgroundColor: 'rgba(50,50,50,0.9)',
                borderColor: 'rgba(255,255,255,0.3)',
                textStyle: {
                  color: '#fff',
                  fontSize: 12
                },
                padding: [8, 10]
              },
              xAxis: {
                type: 'time',
                data: xAxisData,
                axisLine: { show: false },
                axisTick: { show: false },
                axisLabel: {
                  color: 'rgba(255, 255, 255, 0.8)',
                  fontSize: 12,
                  hideOverlap: true,
                  formatter: (value: string) => {
                    return dayjs(value).format('HH:mm');
                  }
                },
                splitNumber: 4
              },
              yAxis: {
                type: 'value',
                show: true,
                axisLine: { show: false },
                axisTick: { show: false },
                splitLine: { show: true, lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } },
                axisLabel: {
                  show: true,
                  color: 'rgba(255, 255, 255, 0.8)',
                  fontSize: 12,
                  formatter: (value: number) => value.toFixed(2)
                },
                splitNumber: 4, // 建议4~6之间
                // 修改：考虑上下限值的y轴范围设置
                min: (value: any) => {
                  const calcMin = Math.floor(value.min) * 0.9;
                  return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
                },
                max: (value: any) => {
                  const calcMax = Math.ceil(value.max) * 1.1;
                  return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
                },
              },
              series: [
                {
                  name: '实际值',
                  data: singleTrendData.values,
                  type: 'line',
                  smooth: true,
                  showSymbol: false,
                  itemStyle: {
                    color: '#fff',
                    borderColor: mainColor,
                    borderWidth: 1,
                  },
                  lineStyle: {
                    color: mainColor,
                    width: 2,
                  },
                  ...getLimitMarkOptions()
                },
              ],
            };
          }

          // 分割数据
          const actualTimes = singleTrendData.times.slice(0, splitIndex);
          const actualValues = singleTrendData.values.slice(0, splitIndex);
          const predictTimes = singleTrendData.times.slice(splitIndex);
          const predictValues = singleTrendData.values.slice(splitIndex);

          // 创建实际值和预测值的两个系列
          return {
            grid: {
              left: 10,
              right: 15,
              top: 10, // 为图例留出空间
              bottom: 10,
              containLabel: true
            },
            tooltip: {
              trigger: 'axis',
              formatter: function (params: any) {
                // 获取当前悬浮的点的数据
                const dataIndex = params[0].dataIndex;

                // 判断当前点是实际值还是预测值
                let isActualValue = params[0].seriesName === '实际值';
                let result = `<div style="font-weight:bold;margin-bottom:3px;">${dayjs(isActualValue ? actualTimes[dataIndex] : predictTimes[dataIndex]).format('YYYY-MM-DD HH:mm:ss')}</div>`;

                // 遍历所有系列添加到tooltip中
                params.forEach((param: any) => {
                  const color = param.seriesName === '实际值' ? mainColor : 
                                param.seriesName === '预测值' ? mainColor : 
                                param.color || mainColor;
                  const seriesName = param.seriesName;
                  const value = param.value instanceof Array ? param.value[1] : param.value;

                  result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                    <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${color}"></span>
                    <span style="flex:1">${seriesName}:</span>
                    <span style="font-weight:bold;float:right">${value}</span>
                  </div>`;
                });

                // 添加上限值和下限值（如果存在）
                if (upperLimit !== undefined) {
                  result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                    <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
                    <span style="flex:1">上限值:</span>
                    <span style="font-weight:bold;float:right">${upperLimit}</span>
                  </div>`;
                }

                if (lowerLimit !== undefined) {
                  result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                    <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
                    <span style="flex:1">下限值:</span>
                    <span style="font-weight:bold;float:right">${lowerLimit}</span>
                  </div>`;
                }

                return result;
              },
              backgroundColor: 'rgba(50,50,50,0.9)',
              borderColor: 'rgba(255,255,255,0.3)',
              textStyle: {
                color: '#fff',
                fontSize: 12
              },
              padding: [8, 10]
            },
            xAxis: {
              type: 'time',
              data: xAxisData,
              axisLine: { show: false },
              axisTick: { show: false },
              axisLabel: {
                color: 'rgba(255, 255, 255, 0.8)',
                fontSize: 12,
                hideOverlap: true,
                formatter: (value: string) => {
                  return dayjs(value).format('HH:mm');
                }
              },
              splitNumber: 4,
              axisPointer: {
                value: dayjs(predictTime).format('HH:mm'),
                snap: true,
                lineStyle: {
                  color: 'rgba(255, 255, 255, 0.5)',
                  width: 1,
                  type: 'dashed'
                },
                label: {
                  show: true,
                  formatter: function () {
                    return '预测时间点';
                  },
                  backgroundColor: 'rgba(50, 50, 50, 0.7)'
                },
                handle: {
                  show: false
                }
              }
            },
            yAxis: {
              type: 'value',
              show: true,
              axisLine: { show: false },
              axisTick: { show: false },
              splitLine: { show: true, lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } },
              axisLabel: {
                show: true,
                color: 'rgba(255, 255, 255, 0.8)',
                fontSize: 12,
                formatter: (value: number) => value.toFixed(2)
              },
              splitNumber: 4, // 建议4~6之间
              // 修改：考虑上下限值的y轴范围设置
              min: (value: any) => {
                const calcMin = Math.floor(value.min) * 0.9;
                return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
              },
              max: (value: any) => {
                const calcMax = Math.ceil(value.max) * 1.1;
                return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
              },
            },
            series: [
              {
                name: '实际值',
                data: actualValues.map((value, index) => [xAxisData[index], value]),
                type: 'line',
                smooth: true,
                showSymbol: false,
                itemStyle: {
                  color: '#fff',
                  borderColor: mainColor,
                  borderWidth: 1,
                },
                lineStyle: {
                  color: mainColor,
                  width: 2,
                },
                ...getLimitMarkOptions()
              },
              {
                name: '预测值',
                data: predictValues.map((value, index) => [xAxisData[splitIndex + index], value]),
                type: 'line',
                smooth: true,
                showSymbol: false,
                itemStyle: {
                  color: '#fff',
                  borderColor: mainColor,
                  borderWidth: 1,
                },
                lineStyle: {
                  color: mainColor,
                  width: 2,
                  type: 'dashed' // 使用虚线表示预测值
                }
              }
            ]
          };
        }

        return {
          grid: {
            left: 10, // 增加左侧空间以显示y轴刻度
            right: 15,
            top: 10,
            bottom: 10,
            containLabel: true
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (params: any) {
              const dataIndex = params[0].dataIndex;
              const time = singleTrendData.times[dataIndex];
              let result = `<div style="font-weight:bold;margin-bottom:3px;">${dayjs(time).format('YYYY-MM-DD HH:mm:ss')}</div>`;

              // 添加实际值 - 使用系列名称
              params.forEach((param: any) => {
                const color = param.color || mainColor;
                const seriesName = param.seriesName || '实际值';
                const paramValue = param.value instanceof Array ? param.value[1] : param.value;

                result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${color}"></span>
                  <span style="flex:1">${seriesName}:</span>
                  <span style="font-weight:bold;float:right">${paramValue}</span>
                </div>`;
              });

              // 添加上限值和下限值（如果存在）
              if (upperLimit !== undefined) {
                result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
                  <span style="flex:1">上限值:</span>
                  <span style="font-weight:bold;float:right">${upperLimit}</span>
                </div>`;
              }

              if (lowerLimit !== undefined) {
                result += `<div style="display:flex;justify-content:space-between;align-items:center;margin:3px 0">
                  <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:rgba(255,255,255,0.5)"></span>
                  <span style="flex:1">下限值:</span>
                  <span style="font-weight:bold;float:right">${lowerLimit}</span>
                </div>`;
              }

              return result;
            },
            backgroundColor: 'rgba(50,50,50,0.9)',
            borderColor: 'rgba(255,255,255,0.3)',
            textStyle: {
              color: '#fff',
              fontSize: 12
            },
            padding: [8, 10]
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
              formatter: (value: string) => {
                return dayjs(value).format('HH:mm');
              },
              hideOverlap: true,
            },
            splitNumber: 4,
          },
          yAxis: {
            type: 'value',
            show: true,
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: true, lineStyle: { color: 'rgba(255, 255, 255, 0.1)' } },
            axisLabel: {
              show: true,
              color: 'rgba(255, 255, 255, 0.8)',
              fontSize: 12,
              formatter: (value: number) => value.toFixed(2)
            },
            splitNumber: 4, // 建议4~6之间
            // 修改：考虑上下限值的y轴范围设置
            min: (value: any) => {
              const calcMin = Math.floor(value.min) * 0.9;
              return lowerLimit !== undefined ? Math.min(calcMin, lowerLimit) : calcMin;
            },
            max: (value: any) => {
              const calcMax = Math.ceil(value.max) * 1.1;
              return upperLimit !== undefined ? Math.max(calcMax, upperLimit) : calcMax;
            },
          },
          series: [
            {
              name: '实际值', // 添加系列名称
              data: singleTrendData.values,
              type: 'line',
              smooth: true,
              showSymbol: false,
              itemStyle: {
                color: '#fff',
                borderColor: mainColor,
                borderWidth: 1,
              },
              lineStyle: {
                color: mainColor,
                width: 2,
              },
              ...getLimitMarkOptions()
            },
          ],
        };
      }
    } else {
      return {}
    }
  };

  // 计算信息卡片的样式
  const infoCardStyle = useMemo(() => {
    if (!markerPixelPosition || !selectedMarker) return {};
    const { width } = viewportSize;

    // 基础样式
    const style = {
      position: 'absolute',
      left: `${markerPixelPosition.x + 20}px`,
      top: `${markerPixelPosition.y - 30}px`,
      transform: 'translate(20px, -50%)',
      animation: 'fadeIn 0.3s ease-out',
    };

    // 如果靠近视口右边缘，调整卡片位置到左侧
    if (markerPixelPosition.x > width * 0.55) {
      style.transform = 'translate(calc(-100% - 3rem), -50%)';
      style.animation = 'fadeInLeft 0.3s ease-out';
    }

    return style;
  }, [markerPixelPosition, selectedMarker, viewportSize.width, isQuestionMode, currentKey]);

  // 计算连接线的样式
  const connectorLineStyle = useMemo(() => {
    if (!markerPixelPosition || !selectedMarker) return {};
    const { width } = viewportSize;
    const isRightSide = markerPixelPosition.x > width * 0.55;

    // 设置不同方向的连接线长度
    const lineLength = 40; // 不同方向使用相同的基础长度

    // 基础样式
    const style: any = {
      position: 'absolute',
      left: `${markerPixelPosition.x}px`,
      top: `${markerPixelPosition.y}px`,
      width: `${lineLength}px`,
      transform: 'translateY(-50%)',
      transformOrigin: 'left center',
    };

    // 根据卡片显示位置确定连接线的方向
    if (isRightSide) {
      // 如果卡片在标记点左侧显示
      style.transform = 'translateY(-50%) rotate(180deg)';
    }

    return style;
  }, [markerPixelPosition, selectedMarker, viewportSize.width]);

  // 获取卡片背景色的类名
  const getCardClassName = (type: string) => {
    return classNames(
      styles["info-card"],
      {
        [styles["card-red"]]: type === 'red',
        [styles["card-yellow"]]: type === 'yellow',
        [styles["card-green"]]: type === 'green',
        [styles["transparent"]]: isTransparent, // 添加透明样式类
      }
    );
  };

  // 获取标记点的类名
  const getMarkerClassName = (type: string) => {
    return classNames(
      styles["marker-point"],
      {
        [styles["marker-red"]]: type === 'red',
        [styles["marker-yellow"]]: type === 'yellow',
        [styles["marker-green"]]: type === 'green',
        [styles["marker-question"]]: isQuestionMode || currentKey === 'param', // question模式或param模式下添加特殊样式
        [styles["transparent"]]: isTransparent, // 添加透明样式类
      }
    );
  };

  // 获取脉冲效果的类名
  const getPulseClassName = (type: string) => {
    return classNames(
      styles["marker-pulse"],
      {
        [styles["pulse-red"]]: type === 'red',
        [styles["pulse-yellow"]]: type === 'yellow',
        [styles["pulse-green"]]: type === 'green',
        [styles["pulse-question"]]: isQuestionMode || currentKey === 'param', // question模式或param模式下添加特殊样式
        [styles["transparent"]]: isTransparent, // 添加透明样式类
      }
    );
  };

  // 获取连接线的类名
  const getConnectorClassName = (type: string) => {
    return classNames(
      styles["connector-line"],
      {
        [styles["connector-red"]]: type === 'red',
        [styles["connector-yellow"]]: type === 'yellow',
        [styles["connector-green"]]: type === 'green',
        [styles["connector-question"]]: isQuestionMode || currentKey === 'param', // question模式或param模式下添加特殊样式
        [styles["transparent"]]: isTransparent, // 添加透明样式类
      }
    );
  };

  if (!selectedMarker || !markerPixelPosition) return null;

  // 获取状态文本
  const getStatusText = () => {
    // 如果是多线图（param模式），显示多个标签名称
    if (currentKey === 'param' && Array.isArray(currentTrendData) && currentTrendData.length > 1) {
      return "参数趋势";
    }
    // 单线图情况，使用异常原因
    const singleTrendData = Array.isArray(currentTrendData)
      ? currentTrendData[0]
      : currentTrendData;
    console.log("singleTrendData", singleTrendData);
    return singleTrendData?.abnormalCause || "";
  };

  // 检查是否为多线图
  const isMultiLine = currentTrendData && Array.isArray(currentTrendData) && currentTrendData.length > 1;

  // 点击图表点的事件处理函数
  const handleChartClick = (params: any) => {
    console.log("handleChartClick", params);
    if (params.componentType !== 'series') return;

    // 获取原始时间数据（如果有）
    let originalName = params.name;

    if (!isMultiLine && currentTrendData) {
      const singleTrendData = Array.isArray(currentTrendData)
        ? currentTrendData[0]
        : currentTrendData;

      if (singleTrendData && singleTrendData.times && params.dataIndex !== undefined) {
        originalName = singleTrendData.times[params.dataIndex];
      }
    }

    // 构建点击数据
    const pointData = {
      name: originalName,
      value: params.value,
      dataIndex: params.dataIndex,
      seriesIndex: params.seriesIndex
    };

    // 如果提供了外部回调函数，则调用
    if (onChartPointClick) {
      onChartPointClick(pointData);
    }
  };

  const handelAsk = () => {
    let vList = [
      `查看${selectedMarker.title}报警详细信息`,
      // `${selectedMarker.title}未来变化趋势怎么样，并统计最近一周异常发生频次、异常原因和解决方案`,
    ];
    let tValue = sample(vList);
    chatRef?.current?.handleChat(tValue);
  }
  return (
    <>
      {/* 标记点 */}
      <div
        className={getMarkerClassName(selectedMarker.type)}
        style={{
          left: `${markerPixelPosition.x}px`,
          top: `${markerPixelPosition.y}px`
        }}
      />

      {/* 脉冲效果 */}
      <div
        className={getPulseClassName(selectedMarker.type)}
        style={{
          left: `${markerPixelPosition.x}px`,
          top: `${markerPixelPosition.y}px`
        }}
      />

      {/* 连接线 */}
      <div
        className={getConnectorClassName(selectedMarker.type)}
        style={connectorLineStyle as any}
      />

      {/* 信息卡片 - 使用类名控制背景色 */}
      <div
        className={getCardClassName(selectedMarker.type)}
        style={infoCardStyle as any}
      >
        <div className={styles["header"]}>
          <div className={styles["title"]} title={selectedMarker.title}>
            {selectedMarker.title}
          </div>
          <div className={styles["btn-container"]}>
            <div className={styles.spanIcon} onClick={() => onSpanClick?.(currentTrendData)} />
          </div>
        </div>

        <div className={styles["content"]}>
          <div className={styles["status-info"]}>
            {
              !hideContentTitle && (
                <div className={styles["status-text"]} title={getStatusText()}>
                  {getStatusText()}
                </div>
              )
            }
            {!hideContentTitle && (
              <div className={styles["detail-link"]} onClick={() => {
                handelAsk()
              }}>查看详情 &gt;&gt;</div>
            )}
          </div>
          <div className={styles["chart"]}>
            <div className={styles["chart-container"]}>
              <ReactECharts
                option={getChartOptions(selectedMarker.type)}
                style={{ height: '100%', width: '100%' }}
                opts={{ renderer: 'canvas' }}
                onEvents={{
                  click: handleChartClick
                }}
              />
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default MarkerInfo;